package com.project.erp.common.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 
 * COPYRIGHT (C) 2013 BY XXX公司

 *  功能模块名：系统-工具类

 *  功能描述：Excel操作工具类

 * @author LiJiaGuo    

 * @version 1.0  

 * @created 2014-1-13 下午5:48:08
 */
public class ExcelUtils {
	protected final Logger logger = LoggerFactory.getLogger(getClass());
	private List<String> items;
	private List<List<String>> datas;
	
	public ExcelUtils(List<String> items,List<List<String>> datas){
		this.items = items;
		this.datas = datas;
	}
	
	/**
	 * 取得规则excel的工作本
	 * @return
	 */
	public HSSFWorkbook getExcelBook(){
		//创建工作薄
		HSSFWorkbook workbook = new HSSFWorkbook();  
		//创建工作表
		HSSFSheet sheet = workbook.createSheet("sheet1");
		
		try {
			//创建表头
			HSSFRow headRow = sheet.createRow(0);
			for(int i=0;i<items.size();i++){
				String name = items.get(0);
				HSSFCell cell = headRow.createCell(i);  
				cell.setCellValue(name);   
			}
			
			//创建数据
			for(int i=1;i<datas.size();i++){
				List<String> data = datas.get(i);
				HSSFRow dataRow = sheet.createRow(0);
				for(int j=0;j<data.size();j++){
					HSSFCell cell = dataRow.createCell(j);
					String dataStr = data.get(0);
					cell.setCellValue(dataStr);   
				}
			}
		} catch (Exception e) {
			logger.error("ExcelUtils getExcelBook Error:"+e.toString());
		}
		
		return workbook;
	}
	
	/**
	 * 取得规则excel的输出流
	 * @return
	 */
	public ByteArrayInputStream getExcelOutputStream(){
		//创建工作薄
		HSSFWorkbook workbook = new HSSFWorkbook();  
		//创建工作表
		HSSFSheet sheet = workbook.createSheet("sheet1");
		ByteArrayInputStream bais = null;
		try {
			//创建表头
			HSSFRow headRow = sheet.createRow(0);
			for(int i=0;i<items.size();i++){
				String name = items.get(i);
				HSSFCell cell = headRow.createCell(i);  
				cell.setCellValue(name);   
			}
			
			//创建数据
			for(int i=0;i<datas.size();i++){
				List<String> data = datas.get(i);
				HSSFRow dataRow = sheet.createRow(i+1);
				for(int j=0;j<data.size();j++){
					HSSFCell cell = dataRow.createCell(j);
					String dataStr = data.get(j);
					cell.setCellValue(dataStr);   
				}
			}
			
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
	        try {
	            workbook.write(baos);
	        } catch (IOException e) {
	            e.printStackTrace();
	        }
	        byte[] ba = baos.toByteArray();
	        bais = new ByteArrayInputStream(ba);
		} catch (Exception e) {
			logger.error("ExcelUtils getExcelBook Error:"+e.toString());
		}
        
        return bais; 
	}
}
